from rtdt.models import RTDTRecord

from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_init
from django.core.cache import cache
from django.conf import settings

from functools import wraps

from rtdt import _rtdt_registered_models

def rtdt_cache_page(timeout = None, dynamic = False):

    def wrap(f):

        @wraps(f)
        def wrapped_f(request, *args, **kwargs):
            # We never handle POST requests, and we only handle GET
            # requests if dynamic is True
            if request.POST or (request.GET and not dynamic):
                return f(request, *args, **kwargs)

            path = request.get_full_path()

            resp = cache.get(path)
            if resp is None:
                # The cache entry could have timed out, so just to be
                # thorough we delete all RTDTRecords for this path
                RTDTRecord.objects.filter(path=path).delete()

                def callback(sender, instance, **kwargs):
                    if not sender in _rtdt_registered_models:
                        return

                    if settings.DEBUG:
                        print 'RTDT: Connecting "%s" with "%s"' % \
                            (path, instance)

                    dr, created = RTDTRecord.objects.get_or_create(
                        mid=instance.id,
                        model=ContentType.objects.get_for_model(instance),
                        path=path)

                post_init.connect(callback)

                resp = f(request, *args, **kwargs)

                if timeout:
                    cache.set(path, resp, timeout)
                else:
                    # Pick up whatever the default cache time is for
                    # this project
                    cache.set(path, resp)

            return resp

        return wrapped_f

    return wrap
